<?php

class WithdrawController extends Controller {

    public $layout = '//layouts/column2';

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('view'),
                //'users' => array('*'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create',),
                'users' => array('@'),
            //'expression'=>'$user->isAdmin()'
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'admin', 'delete', 'update', 'confirm'),
                //'users' => array('admin'),
                'expression' => '$user->isAdmin()'
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionConfirm($id) {
        if ($id) {
            $model = Withdraw::model()->findByPk($id);
            /* $balance = $this->getCurrentBalance($model->member_id);
              $mthModel = new MemberTransactionHistory();
              $mthModel->member_id = $model->member_id;
              $mthModel->credit = 0;
              $mthModel->debit = $model->amount;
              $mthModel->transaction_date = date("Y-m-d H:i:s");
              $mthModel->balance = $balance - $model->amount;
              $mthModel->particulars = "Withdraw " . $model->method;
              $mthModel->payment_processors_id = $model->method;
              $mthModel->save();
              $model->member_transaction_id = $mthModel->member_transaction_history_id;
             */
            $model->status = 1;
            $model->update();

            $superid = Member::model()->find("member_type=:member_type", array('member_type' => LevelLookUp::SUPERADMIN))->member_id;
            $sbalance = $this->getCurrentUserBalance($superid);
            $smthModel = new MemberTransactionHistory();
            $smthModel->member_id = $superid;
            $smthModel->credit = 0;
            $smthModel->debit = $model->amount;
            $smthModel->transaction_date = date("Y-m-d H:i:s");
            $smthModel->balance = $sbalance - $model->amount;
            $smthModel->particulars = "Withdraw approval";
            $smthModel->payment_processors_id = $model->method;
            ;
            $smthModel->ref_id = Yii::app()->user->id;
            $smthModel->save();

            $member = Member::model()->findByPk($model->member_id);
            $headers = "From: Financial Department<".Yii::app()->params['paymentEmail'].">\r\n" .
                    "Reply-To: ".Yii::app()->params['paymentEmail']."\r\n" .
                    "MIME-Version: 1.0\r\n" .
                    "Content-type: text/plain; charset=UTF-8";
            $body = "Dear " . $member->username . ",\nYour withdraw request successfully transferred to your requested payment processor account. Please verify your associate payment processor account. \n\n - Thanks, The ViewInvesta Team";
            mail($member->email, "ViewInvesta Withdraw Notification", $body, $headers);
        }
        $this->actionAdmin();
    }

    public function actionCreate() {
        $model = new Withdraw;
        $rBalance = 10;
        $balance = $this->getCurrentUserBalance(Yii::app()->user->id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Withdraw'])) {
            $criteria = new CDbCriteria();
            $criteria->addCondition('member_id=' . Yii::app()->user->id);
            $withdraw = Withdraw::model()->findAll($criteria);
            if (empty($withdraw)) {
//                $mthModel = new MemberTransactionHistory();
//                $mthModel->member_id = Yii::app()->user->id;
//                $mthModel->credit = 0;
//                $mthModel->debit = 10;
//                $mthModel->transaction_date = date("Y-m-d H:i:s");
//                $mthModel->balance = $balance - 10;
//                $mthModel->particulars = "Deduct initial 10 dolor as given on new regiestration";
//                $mthModel->positions = 0;
//                $mthModel->save();
//                $balance = $balance - 10;
            }
            $model->attributes = $_POST['Withdraw'];
            if (!isset($model->amount)) {
                $model->amount = 0;
            }
            if ($balance < $rBalance) {
                Yii::app()->user->setFlash('error', "You do not have enough balance, minimum balance $" . $rBalance . " is required for widthdraw.");
                $this->render('create', array(
                    'model' => $model,
                ));
            } else if ($balance < $model->amount) {
                Yii::app()->user->setFlash('error', "You do not have enough balance for this widthdraw.");
                $this->render('create', array(
                    'model' => $model,
                ));
            } else {
                $model->status = 0;
                $model->request_date = date("Y-m-d H:i:s");
                $model->member_id = Yii::app()->user->id;
                
                $memberAccount = MemberAccount::model()->find("member_id=:member_id AND payment_processors_id=:payment_processors_id", array("member_id" => Yii::app()->user->id, "payment_processors_id" => $model->method));
                $pp = PaymentProcessor::model()->findByAttributes(array('payment_processors_id' => $model->method));
                
                $model->member_account_id = $memberAccount->member_account_id;
                if ($model->save()) {
                    $mthModel = new MemberTransactionHistory();
                    $mthModel->member_id = Yii::app()->user->id;
                    $mthModel->credit = 0;
                    $mthModel->debit = $model->amount;
                    $mthModel->transaction_date = date("Y-m-d H:i:s");
                    $mthModel->balance = $balance - $model->amount;
                    $mthModel->particulars = "Withdraw " . $model->amount;
                    $mthModel->payment_processors_id = $model->method;
                    $mthModel->isWithdraw = "1";
                    if($pp->charge != null){
                        $chargedamount = ($model->amount*$pp->charge)/100;
                        $mthModel->charged_amount = $chargedamount;
                    }
                    if($mthModel->save()){
                        $model->member_transaction_id = $mthModel->member_transaction_history_id;
                        $model->save();
                        $this->redirect(array('view', 'id' => $model->id));
                    }
                }
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    function getCurrentBalance($id) {
        $sql = "select * from member_transaction_history where member_transaction_history_id = (
                    select max( member_transaction_history_id ) from member_transaction_history 
                    where member_id =" . $id . ")";

        $_lh = Yii::app()->db->createCommand($sql)->queryAll();
        $balance = 0;
        if (!empty($_lh)) {
            $_history = $_lh[0];
            if (!empty($_history)) {
                $balance = $_history['balance'];
            }
        }
        return $balance;
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Withdraw'])) {
            $model->attributes = $_POST['Withdraw'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Withdraw');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Withdraw('search', array(
                    'criteria' => array('condition' => 'status=0')
                ));
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Withdraw']))
            $model->attributes = $_GET['Withdraw'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function loadModel($id) {
        $model = Withdraw::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Withdraw $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'withdraw-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}